package com.itcam.reflect_.msb03;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

/**
 * Author:Cammy.Wu
 * Date:2024-05-21
 * Description:
 */
/**
 *
 */
public class Test02 {

    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 获取运行时类的字节码信息
        Class cls = Student.class;

        // 获取属性
        // getFields：获取运行时类中被public修饰的属性
        Field[] fields = cls.getFields();
        for (Field field : fields) {
            System.out.println("field = " + field);
        }
        System.out.println("----------------------------------------------");
        // getDeclaredFields:获取运行时类中的所有属性
        Field[] declaredFields = cls.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println("declaredField = " + declaredField);
        }
        System.out.println("----------------------------------------------");
        // 获取指定的属性
        Field score = cls.getField("score");
        System.out.println("score = " + score);
        Field sno = cls.getDeclaredField("sno");
        System.out.println("sno = " + sno);
        System.out.println("----------------------------------------------");

        // 属性的具体结构
        // 获取修饰符
//        int modifiers = sno.getModifiers();
//        System.out.println("modifiers = " + modifiers);
//        System.out.println(Modifier.toString(modifiers));
        System.out.println(Modifier.toString(sno.getModifiers()));

        // 获取属性的数据类型
        Class type = sno.getType();
        System.out.println("type = " + type);

        // 获取属性的名字
        String name = sno.getName();
        System.out.println("name = " + name);

        System.out.println("----------------------------------------------");

        // 给属性赋值（给属性设置值，必须要有对象）
        Field sco = cls.getField("score");
        Object o = cls.getDeclaredConstructor().newInstance();
        sco.set(o,98); // 给o这个对象的score属性设置具体的值
        System.out.println("o = " + o);
    }


}
